package logic

import (
	"context"
	"fmt"

	"probe-scheduler/internal/svc"
	pb "probe-scheduler/pb/scheduler"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateTaskLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTaskLogic {
	return &UpdateTaskLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 验证任务配置
func (l *UpdateTaskLogic) validateTask(task *pb.Task) error {
	if task.ProbeConfig == nil {
		return fmt.Errorf("probe config is required")
	}

	if task.ProbeConfig.Target == "" {
		return fmt.Errorf("probe target is required")
	}

	switch task.Type {
	case pb.TaskType_CRON, pb.TaskType_PERIODIC:
		if task.CronExpression == "" {
			return fmt.Errorf("cron expression is required for cron/periodic tasks")
		}
	case pb.TaskType_RECURRING:
		if task.Interval <= 0 {
			return fmt.Errorf("interval must be greater than 0 for recurring tasks")
		}
	}

	return nil
}

func (l *UpdateTaskLogic) UpdateTask(in *pb.UpdateTaskRequest) (*pb.UpdateTaskResponse, error) {
	if in.Task == nil || in.Task.Id == 0 {
		return &pb.UpdateTaskResponse{
			Base: &pb.CommonResponse{
				Success: false,
				Message: "task and task id are required",
			},
		}, nil
	}

	// 验证任务配置
	if err := l.validateTask(in.Task); err != nil {
		return &pb.UpdateTaskResponse{
			Base: &pb.CommonResponse{
				Success: false,
				Message: err.Error(),
			},
		}, nil
	}

	// 更新数据库
	if err := l.svcCtx.TaskDao.UpdateTask(l.ctx, in.Task); err != nil {
		return &pb.UpdateTaskResponse{
			Base: &pb.CommonResponse{Success: false, Message: fmt.Sprintf("更新失败: %v", err)},
		}, nil
	}

	// 更新任务
	err := l.svcCtx.Scheduler.UpdateTask(l.ctx, in.Task)
	if err != nil {
		l.Errorf("failed to update task %s: %v", in.Task.Id, err)
		return &pb.UpdateTaskResponse{
			Base: &pb.CommonResponse{
				Success: false,
				Message: fmt.Sprintf("failed to update task: %v", err),
			},
		}, nil
	}

	return &pb.UpdateTaskResponse{
		Base: &pb.CommonResponse{
			Success: true,
			Message: "task updated successfully",
		},
	}, nil
}
